/*
 * @Description: 新增元数据弹窗组件
 * @Author: Rfan
 * @Date: 2022-01-07 14:54:11
 * @LastEditTime: 2022-10-26 15:29:22
 */

import { FC, useEffect, useState } from 'react';
import { Button, Form, Modal } from 'antd';
import { useMetadataContext } from '../../contexts/MetaContext';
import { fetchAliasList } from '@/api/metadata';
import { getListItemValue } from '@/utils/list';
import MetadataForm from '@/view/system/Metadata/components/dialogs/common/MetadataForm';
import type { ICommonDialog } from '@/interfaces/global';

interface AddDialogProps extends ICommonDialog {}

const AddDialog: FC<AddDialogProps> = (props) => {
  const { visible, onClose } = props;
  const { addMetadataFunc } = useMetadataContext();
  const [form] = Form.useForm();

  // 字典表类型
  const [dicType, setDicType] = useState(1);
  // 别名列表
  const [aliasList, setAliasList] = useState([]);
  // 保存按钮loading状态
  const [addLoading, setAddLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      getAliasList();
    }
  }, [visible, dicType]);

  const getAliasList = () => {
    fetchAliasList().then((res) => {
      setAliasList(res.data);
    });
  };

  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  // 新增档案类型
  const onFinish = (values: any) => {
    values.allowed_dup = values.allowed_dup ? 0 : 1;
    values.allowed_null = values.allowed_null ? 0 : 1;
    if (values.business_concept_id) {
      values.business_concept_name = getListItemValue(
        values.business_concept_id,
        aliasList,
        'cName'
      );
    }
    setAddLoading(true);
    addMetadataFunc(values)
      .then(() => {
        onClose();
      })
      .finally(() => {
        setAddLoading(false);
      });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const onCancel = () => {
    if (dicType !== 1) {
      setDicType(1);
    }
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="新建字段"
      visible={visible}
      width={600}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={addLoading} onClick={submitFunc}>
          保存
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        preserve={false}
        initialValues={{
          delete: 0,
          field_type: 0,
          field_kind: 1,
          default_value: '',
          allowed_dup: true,
          allowed_null: true
        }}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <MetadataForm
          visible={visible}
          dicType={dicType}
          setDicType={setDicType}
          aliasList={aliasList}
        />
      </Form>
    </Modal>
  );
};

export default AddDialog;
